import socket
import sys
import time

def test_tcp_connection(server_ip, server_port, timeout=5):
    print(f"=== TCP连接测试工具 ===")
    print(f"服务器IP: {server_ip}")
    print(f"服务器端口: {server_port}")
    print(f"超时设置: {timeout}秒")
    print("====================")

    try:
        # 创建TCP套接字
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        print(f"正在尝试连接到 {server_ip}:{server_port}...")

        start_time = time.time()
        result = sock.connect_ex((server_ip, server_port))
        end_time = time.time()

        if result == 0:
            print(f"连接成功！耗时: {end_time - start_time:.2f}秒")
            print("服务器正在监听该端口。")
            return True
        else:
            print(f"连接失败，错误码: {result}")
            print("可能的原因:")
            print("1. 服务器IP或端口不正确")
            print("2. 服务器未运行或未监听该端口")
            print("3. 网络连接问题或防火墙阻止")
            return False
    except Exception as e:
        print(f"测试失败: {str(e)}")
        return False
    finally:
        try:
            sock.close()
        except:
            pass

if __name__ == "__main__":
    # 默认参数
    server_ip = "192.168.43.1"
    server_port = 443
    timeout = 5

    # 如果有命令行参数，则使用命令行参数
    if len(sys.argv) > 1:
        server_ip = sys.argv[1]
    if len(sys.argv) > 2:
        server_port = int(sys.argv[2])
    if len(sys.argv) > 3:
        timeout = int(sys.argv[3])

    success = test_tcp_connection(server_ip, server_port, timeout)

    if success:
        print("\n测试成功！服务器可达。")
    else:
        print("\n测试失败，请检查上述问题。")